﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Linq.Expressions;

namespace CoolCode.Tests.Data.Entity
{
    public class DataContext
    {
        public static  readonly DataContext Context = new DataContext();
        Type t;
        public void   Setup(Type type)  
        {
            t = type;
        }

        public ObjectContext Provide()
        {
            object obj =Activator.CreateInstance(t);
            obj.ThrowIfNull("ObjectContext");
            return (ObjectContext)obj;
        }
    }

    //public abstract class RespositoryBase<TContext, TEntity> where TContext : ObjectContext, new()
    //{
    //    protected TContext _context = new TContext();
    //}

    public class Respository<T> 
    {
        //private NorthwindEntities _context;
        //private XContext  _context;
        private ObjectContext _context;


        public Respository()
        {
            //_context = new NorthwindEntities();
            //_context = new XContext();
            _context =  DataContext.Context.Provide();
        }


        private ObjectQuery<T> _table = null;

        protected virtual ObjectQuery<T> table
        {
            get
            {
                if (_table == null)
                    _table = _context.CreateQuery<T>("[" + typeof(T).Name + "]");
                return _table;
            }
        }

        public virtual void Insert(T entity)
        {
            _context.AddObject(typeof(T).Name, entity);
        }

        public virtual IQueryable<T> Query()
        {
            return table;
        }

        public virtual IQueryable<T> Query(Expression<Func<T, bool>> predicate)
        {
            return table.Where(predicate);
        }

        public virtual void Submit()
        {
            _context.SaveChanges();
        }
    }
}
